package com.cloudboy.redisConsole.jedis;

import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.cloudboy.redisConsole.model.MyRedisData;
import com.cloudboy.redisConsole.model.MyRedisDatabase;
import com.cloudboy.redisConsole.model.MyRedisKeyValue;
import com.thoughtworks.xstream.XStream;

import redis.clients.jedis.Jedis;

@SpringBootApplication
public class JedisApp implements CommandLineRunner {

	private static final Logger LOGGER = LoggerFactory.getLogger(JedisApp.class);
	private static XStream xs = new XStream();
	
	@Autowired
	private MyJedisPool jedisPool;
	
	private void test() {
		LOGGER.info("testing is started.");
		Jedis jedis = jedisPool.getJedis();
		MyRedisData redisData = new MyRedisData();
		for (int db = 0; db < 16; db++) { // redis缺省分16个database, 编号从0~15
			MyRedisDatabase redisDatabase = new MyRedisDatabase();
			redisData.addDatabase(redisDatabase);
			jedis.select(db);
			redisDatabase.setDatabase(db);
			
			Set<String> keys = jedis.keys("*");
			for (String key : keys) {
				MyRedisKeyValue keyValue = new MyRedisKeyValue();
				redisDatabase.addKeyValue(keyValue);
				keyValue.setKey(key);
				String type = jedis.type(key);
				keyValue.setType(type);
				if ("hash".equals(type)) {
					Map<String, String> hashValue = jedis.hgetAll(key);
					keyValue.setHashValue(hashValue);
				} else if ("string".equals(type)) {
					String stringValue = jedis.get(key);
					keyValue.setStringValue(stringValue);
				} else {
					throw new RuntimeException("not dealed with type:" + type);
				}
			}
		}
		jedis.close();
		LOGGER.info(xs.toXML(redisData));
	}

	public static void main(String[] args) {
		SpringApplication.run(JedisApp.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		this.test();
	}
}
